package com.sc.justification;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import chrriis.common.UIUtils;
import chrriis.dj.nativeswing.swtimpl.NativeInterface;

import com.sc.justification.dao.GenericDao;
import com.sc.justification.model.Menu;


public class AppWindow {

	public static JFrame frame= new JFrame();
	public static JSplitPane splitPane;
	GenericDao<Menu> dao=new GenericDao<Menu>(Menu.class);
	private static List<Menu> menus=new ArrayList<Menu>();
	private JTree tree;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				  UIUtils.setPreferredLookAndFeel();
			      NativeInterface.open();
				try {
					AppWindow window = new AppWindow();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public AppWindow() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		menus=dao.query("select o from Menu o  where o.parent is null");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
		JMenuBar menuBar = new JMenuBar();
		frame.setJMenuBar(menuBar);
		for (Menu record : menus) {
			JMenu menu=new JMenu(record.getName()); 
			
			menuBar.add(menu);
			for(Menu child:record.getChildren()){
				JMenuItem menuItem = new JMenuItem(child.getName());
				menuItem.setAction(ActionBuilder.getAction(child));
				menu.add(menuItem);
				
			}
		}
		
		
		splitPane = new JSplitPane();
		frame.getContentPane().add(splitPane, BorderLayout.CENTER);
		splitPane.setDividerLocation(200);
		JPanel panel = new JPanel();
		splitPane.setRightComponent(panel);
		
		tree = new JTree(MenuTreeModelBuilder.getMenuTreeModel(menus));
		tree.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent e) {
				DefaultMutableTreeNode node=(DefaultMutableTreeNode)e.getPath().getLastPathComponent();
				if(node.isLeaf()){
					ActionBuilder.getAction((Menu)node.getUserObject()).actionPerformed(null);
				}
			}
		});
		tree.setRootVisible(false);
		splitPane.setLeftComponent(tree);
	}

}
